//
//  WNGiftVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/9/18.
//

import UIKit

class WNGiftVC: WNBaseVC {
        
    lazy var giftBomView: GiftBomView = {
        let view = GiftBomView()
        view.giveBtn.rx.tap.bind { [weak self] in
            self?.sendGift()
        }.disposed(by: rx.disposeBag)
        return view
    }()
    
    lazy var giftColView: UICollectionView = {
        let col = UICollectionView(frame: .zero, collectionViewLayout: GiftLayout())
        col.register(GiftColCell.self, forCellWithReuseIdentifier: GiftColCell.identifier)
        col.showsVerticalScrollIndicator = false
        col.showsHorizontalScrollIndicator = false
        col.delegate = self
        col.dataSource = self
        col.backgroundColor = .clear
        col.bounces = false
        col.isPagingEnabled = true
        return col
    }()
    
    lazy var pageControl: ZPageControl = {
        let con = ZPageControl.init(frame: CGRect(x: (ScreenW-60)/2, y: ScreenW*0.7+20, width: 60, height: 15))
        con.currentPageIndicatorTintColor = .init(named: "red_FE95B4")!
        con.pageIndicatorTintColor = .init(named: "gray_D0D0D0")!
        return con
    }()
    
    var giftArr = [GiftModel]() {
        didSet {
            giftColView.reloadData()
            pageControl.isHidden = giftArr.count < 9
            pageControl.numberOfPages = (giftArr.count%8 != 0 ? giftArr.count/8+1 : giftArr.count/8)
        }
    }
    
    var selItem: Int = -1 {
        didSet {
            guard selItem != -1 else {
                return
            }
            giftBomView.giveBtn.setTitle(WNSingleData.shared.userGold < giftArr[selItem].gold ? "儲值" : "贈送", for: .normal)
            giftColView.reloadData()
        }
    }
    
    var sendClosure: StringClosure?
        
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getUserGold { [weak self] gold in
            self?.giftBomView.moneyBtn.setTitle("\(gold)", for: .normal)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        wn_hidNavView()
        view.addSubview(giftBomView)
        view.addSubview(giftColView)
        view.addSubview(pageControl)
        giftBomView.snp.makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.bottom.equalTo(-TabBarMargin)
            make.height.equalTo(44)
        }
        giftColView.snp.makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.bottom.equalTo(giftBomView.snp.top).offset(-12)
            make.height.equalTo(ScreenW*0.7)
        }
        view.wn_cornerCustom([.topLeft, .topRight], 20)
    }
    
    override func dataConfig() {
        giftListRequest()
    }
        
    func sendGift() {
        guard giftArr.count != 0 else {
            return
        }
        guard selItem != -1 else {
            wn_toast("請先選禮物")
            return
        }
        if WNSingleData.shared.userGold < giftArr[selItem].gold {
            wn_pushStoreVC()
        }else {
            gaveGiftRequest()
        }
    }
}

//MARK: - CollectionViewDelegate
extension WNGiftVC: UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return giftArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GiftColCell.identifier, for: indexPath) as! GiftColCell
        cell.model = giftArr[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if selItem == indexPath.item {
            giftArr[indexPath.item].isSelected = !giftArr[indexPath.item].isSelected
            selItem = -1
        }else {
            if selItem != -1 {
                giftArr[selItem].isSelected = false
            }
            selItem = indexPath.item
            giftArr[indexPath.item].isSelected = true
        }
        collectionView.reloadItems(at: [indexPath])
        collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: false)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let page = scrollView.contentOffset.x/ScreenW
        pageControl.currentPage = Int(page)
    }
}

extension WNGiftVC {
    
    func gaveGiftRequest() {
        let giftId = giftArr[selItem].giftNo ?? ""
        let giftName = giftArr[selItem].name ?? ""
        provider_gift.rx.request(.giveGift(baseId, giftId))
            .asObservable().mapModel(BaseModel<String>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                self?.getUserGold { gold in
                    self?.giftBomView.moneyBtn.setTitle("\(gold)", for: .normal)
                }
                if let _ = model.data {
                    self?.sendClosure?("😄謝謝你的 \(giftName)!❤️")
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("檢查網路連線")
            }).disposed(by: rx.disposeBag)
    }
    
    func giftListRequest() {
        provider_gift.rx.request(.giftList)
            .asObservable().mapModel(BaseModel<[GiftModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if let arr = model.data {
                    self?.giftArr = arr
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("檢查網路連線")
            }).disposed(by: rx.disposeBag)
    }
}
